<!-- 组织-组织机构管理-法律实体 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb" subtitle>
        <template #subtitle>
          <a-tooltip content="法律实体是组织注册登记的公司实体信息。">
            <icon-info-circle-fill style="color: #165dff; font-size: 16px" />
          </a-tooltip>
        </template>
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space direction="vertical">
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入公司名称"
            search-button
            v-model="searchVal"
            @search="onSearch"
            @press-enter="onSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </a-space>
      </template>
      <template #right>
        <a-button type="primary" @click="add">新增法律实体</a-button>
        <a-button type="outline" status="danger" @click="del(null)"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>

    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column title="序号" :width="80">
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.dataIndex"
        :title="item.title"
        :data-index="item.dataIndex"
        :width="item.width"
        ellipsis
        :tooltip="{
          position: 'left'
        }"
      >
        <template #cell="{ record }" v-if="item.dataIndex === 'lawId'">
          {{ legalList.find((item: any) => item.id === record.lawId)?.name }}
        </template>
      </a-table-column>

      <!-- <a-table-column :width="100" dataIndex="name" title="是否开启">
        <template #cell="{ record }">
          <a-switch v-model="record.IsEnable" /> </template
      ></a-table-column> -->
      <a-table-column
        dataIndex="workPlace"
        title="操作"
        fixed="right"
        :width="100"
      >
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="headerSettingVisible = !headerSettingVisible"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="详情">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="details(record)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="edit(record)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record.id)"
              >
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space> </template
      ></a-table-column>
    </TableTurn>
  </ContentCard>
  <AddLegalEntity
    v-model:visible="modelVisible"
    :data="addLegalEntityData"
    :title="LegalEntityTitle"
    @addLegalEntity="addLegalEntity"
    :type="type"
  ></AddLegalEntity>
  <FormHeaderSetting
    v-model:visible="headerSettingVisible"
    title="法律实体表头设置"
    :resultList="resultList"
    :forbidList="forbidList"
    :orginHeaderList="orginHeaderList.headerListCode"
    @headerSave="headerSave"
  />
</template>

<script lang="ts" setup>
import {
  GetLegalEntityList,
  postLegalEntity,
  putLegalEntity,
  delLegalEntity
} from '@/apis/management/organization/organizationManagement/LegalEntity/index';
import { getLegalEntityTypeList } from '@/apis/management/organization/baseSetting/LegalEntityType/index';
import AddLegalEntity from './AddLegalEntity.vue';
import { Message, Modal } from '@arco-design/web-vue';
import {
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';

const userId = +(localStorage.getItem('userId') as string);
const title = '法律实体';
const breadCrumb: string[] = ['组织', '组织机构管理', '法律实体'];

const modelVisible = ref(false);
let tableRef = ref(); // 储存table的ref
const addLegalEntityData = ref();
const LegalEntityTitle = ref();
let type = ref(''); // 判断用户点击查看新增、详情还是编辑
/* 储存选择的数据 */

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

let searchVal = ref(''); // 搜索框值

// 表头数据
const tableHeader = [
  {
    title: '公司名称',
    dataIndex: 'name',
    width: 200
  },
  {
    title: '统一社会信用代码',
    dataIndex: 'code',
    width: 200
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 200
  },
  {
    title: '报税区域',
    dataIndex: 'region',
    width: 200
  },
  {
    title: '地址',
    dataIndex: 'address',
    width: 200
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 200
  },

  {
    title: '开户银行',
    dataIndex: 'bank',
    width: 200
  },
  {
    title: '银行账户',
    dataIndex: 'bankNumber',
    width: 200
  },
  {
    title: '备注',
    dataIndex: 'remark',
    width: 200
  }
];
let tableSettingVisible = ref(false); // 是否显示表头设置

// 获取表格数据
const getTableData = async (page: any) => {
  try {
    const res = await GetLegalEntityList({
      ...page,
      name: searchVal.value
    });
    console.log(res);

    // flatData.value = flatTree(res);
    // console.log(flatData.value.length);
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 表头设置所有表头(默认不能移动的表头要放在最前面)
const resultList = [
  {
    title: '公司名称',
    dataIndex: 'name',
    width: 200
  },
  {
    title: '统一社会信用代码',
    dataIndex: 'code',
    width: 200
  },
  {
    title: '类型',
    dataIndex: 'lawId',
    width: 80
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 150
  },
  {
    title: '报税区域',
    dataIndex: 'region',
    width: 200
  },
  {
    title: '地址',
    dataIndex: 'address',
    width: 200
  },

  {
    title: '开户银行',
    dataIndex: 'bank',
    width: 150
  },
  {
    title: '银行账户',
    dataIndex: 'bankNumber',
    width: 150
  },
  {
    title: '备注',
    dataIndex: 'remark',
    width: 200
  }
];
const addHeader = async () => {
  try {
    await PostHeaderSetting({
      userId,
      ownerFuncType: 15, // 法律实体写死15
      headerListCode: resultList.map((item: any) => item.dataIndex).join(',')
    });
    const headerRes = await GetHeaderSetting({
      ownerFuncType: 15,
      userId
    });
    orginHeaderList.value = headerRes;
  } catch (error: unknown) {
    console.log(error);
  }
};
const legalList: any = ref([]);
let forbidList = ref(['name', 'phone']); // 禁止移动的表头
let orginHeaderList = ref([]); // 后端传过来的表头
let headerSettingVisible = ref(false);
let headerSetting = ref<any>([]); // 当前的表头数据
// 获取法律类型数据
const getData = async () => {
  const [headerRes, legalListRes]: any = await Promise.all([
    GetHeaderSetting({
      ownerFuncType: 15,
      userId
    }),
    getLegalEntityTypeList({
      pageNumber: 0,
      pageSize: -1,
      type: 1
    })
  ]);
  orginHeaderList.value = headerRes;
  if (headerRes.headerListCode.length < 1) {
    addHeader();
  }
  headerSetting.value = resultList;
  legalList.value = legalListRes.content;
};
getData();

// 在表格上显示的表头
const selectedHeader = computed(() => {
  let selectedHeaders: any[] = [];
  if (orginHeaderList.value?.id) {
    let temp = headerSetting.value.filter((el: any) =>
      orginHeaderList.value?.headerListCode.includes(el.dataIndex)
    );

    let defaultHeaders = temp.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.dataIndex);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders = defaultHeaders;
    selectedHeaders.sort((a, b) => a.sort - b.sort);
    console.log('====================================');
    console.log(selectedHeaders);
    console.log('====================================');
    // // 将名称移到最前面
    const nameHeaderIndex = selectedHeaders.findIndex(
      (header) => header.dataIndex === 'name'
    );
    if (nameHeaderIndex !== -1) {
      selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
    }
  }

  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.dataIndex).join(',');
    await PutHeaderSetting({
      id,
      userId,
      ownerFuncType: 15,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 搜索框
const onSearch = () => {
  tableRef.value.loadData({
    pageNumber: 0,
    pageSize: -1
  });
};

const add = () => {
  LegalEntityTitle.value = '新增法律实体';
  type.value = 'add';
  addLegalEntityData.value = {
    name: '',
    code: '',
    region: '',
    address: '',
    phone: undefined,
    bank: '',
    bankNumber: undefined,
    remark: '',
    type: undefined
  };
  modelVisible.value = true;
};

const details = (record) => {
  type.value = 'detail';
  LegalEntityTitle.value = '法律实体详情';
  addLegalEntityData.value = record;
  modelVisible.value = true;
};

const edit = (record) => {
  type.value = 'edit';
  LegalEntityTitle.value = '编辑法律实体';
  addLegalEntityData.value = record;
  modelVisible.value = true;
};

const addLegalEntity = async (formData: any, key: string) => {
  console.log(formData);
  if (key === 'add') {
    await postLegalEntity(formData);
  } else if (key === 'edit') {
    await putLegalEntity(formData);
  }
  tableRef.value.loadData();
};

let singleSelectId = 0; // 储存单个id
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

// 删除一项
const del = async (id: number) => {
  try {
    if (!id) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              await delLegalEntity({
                ids: selectedList.value
              });
              tableRef.value.selectedList = [];
              tableRef.value.loadData();
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      await delLegalEntity({
        ids: [id]
      });
      tableRef.value.selectedList = [];
      tableRef.value.loadData();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
// 删除
</script>

<style lang="less" scoped>
.container {
  padding: 10px 20px;
  .header {
  }
  .main {
    margin-top: 20px;
  }
}
</style>
